package com.youbang.base.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class UrlFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 不拦截的url
		String[] notFilter = new String[] { "/login" };

		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String url = httpRequest.getRequestURI();
		boolean doFilter = check(notFilter, url);

		if (doFilter) {
			Object obj = httpRequest.getSession().getAttribute("session");// TODO
			if (null == obj) {

				response.setContentType("text/html;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");

				// 如果session中不存在登录者实体，则弹出框提示重新登录
				PrintWriter out = response.getWriter();
				String loginPage = httpRequest.getContextPath() + "/pages/login/login.jsp";

				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\">");
				builder.append("alert('请登录系统后再进行操作');");
				builder.append("window.top.location.href='");
				builder.append(loginPage);
				builder.append("';");
				builder.append("</script>");
				out.print(builder.toString());
			} else {
				chain.doFilter(request, response);
			}
		} else {
			chain.doFilter(request, response);
		}

	}

	@Override
	public void destroy() {

	}

	/**
	 * @param notFilter
	 *            不拦截的url
	 * @param url
	 *            ：请求的url
	 * @return false：不拦截 true：拦截
	 */
	private boolean check(String[] notFilter, String url) {
		// 以css、js结尾的不进行拦截
		if (url.endsWith(".css") || url.endsWith(".js")) {
			return false;
		}
		// 含有notFilter中的任何一个则不进行拦截
		for (String s : notFilter) {
			if (url.indexOf(s) != -1) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否为Ajax请求
	 * 
	 * @param request
	 * @return 是true, 否false
	 */
	public boolean isAjaxRequest(HttpServletRequest request) {

		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}
}